package com.shloma.bbts.controller;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shloma.bbts.config.FXMLPage;
import com.shloma.bbts.service.UserService;
import com.shloma.bbts.utils.AlertUtil;
import com.shloma.bbts.utils.BeanFactoryUtils;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;

/**
 * 登录控制器
 * <p>
 *
 * @author xuefeng.shi
 * @date 2018/12/04
 * @version v1.0.0
 */
public class LoginController implements Initializable {

	private static Logger logger = LoggerFactory.getLogger(LoginController.class);

	@FXML
	private TextField loginName;
	@FXML
	private PasswordField loginPwd;

	@FXML
	private Button login;
	@FXML
	private Button loginOut;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javafx.fxml.Initializable#initialize(java.net.URL,
	 * java.util.ResourceBundle)
	 */
	public void initialize(URL location, ResourceBundle resources) {
		logger.info("init");

		loginPwd.setOnKeyPressed(event -> {
			if (event.getCode() == KeyCode.ENTER) {
				login();
			}
		});
	}

	@FXML
	public void login() {

		logger.info("用户登录");
		UserService userService = BeanFactoryUtils.getBean(UserService.class);
		if (userService.login(loginName.getText(), loginPwd.getText())) {
			URL url = Thread.currentThread().getContextClassLoader().getResource(FXMLPage.MAIN_UI_PAGE.getFxml());
			FXMLLoader fxmlLoader = new FXMLLoader(url);
			Stage stage = (Stage) login.getScene().getWindow();
			try {
				Parent root = fxmlLoader.load();
				stage.setResizable(true);
				stage.setScene(new Scene(root));
			} catch (IOException e) {
				logger.error("###### 主界面加载失败", e);
				throw new RuntimeException(e);
			}
			stage.show();

			MainUIController controller = fxmlLoader.getController();
			controller.setPrimaryStage(stage);

			// 主窗口关闭事件
			stage.setOnCloseRequest(event -> {
				logger.info("监听到窗口关闭");
				controller.stopServer();
			});
		} else {
			AlertUtil.showWarnAlert("登录失败", "用户名或密码错误");
		}
	}

	@FXML
	public void loginOut() {
		logger.info("界面退出");
		Stage stage = (Stage) loginOut.getScene().getWindow();
		stage.close();
	}
}
